<template>
    <div class="mod-config">
      <div style="text-align:center;">
        <vue2-org-tree
          name="test"
          :data="data"
          :horizontal="horizontal"
          :collapsable="collapsable"
          :label-class-name="labelClassName"
          :render-content="renderContent"
          @on-expand="onExpand"
          @on-node-click="onNodeClick"
        />
      </div>
      <el-form :inline="true" class="queryForm">
        <el-form-item>
          <el-button size="mini" icon="iconfont iconsoushuo" @click="queryHandle()">搜索</el-button>
          <el-button size="mini" icon="iconfont iconlajixiang" v-if="isAuth('certificate:certificateInfo:list')" type="danger" @click="updateParams(0)">垃圾箱</el-button>
          <el-button size="mini" icon="iconfont iconxinzeng" v-if="isAuth('certificate:certificateInfo:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        height="500"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="index"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="gender"
          header-align="center"
          align="center"
          width="60"
          label="性别"
          :formatter="genderFormat">
        </el-table-column>
        <el-table-column
          prop="idCard"
          header-align="center"
          align="center"
          label="身份证号">
        </el-table-column>
        <el-table-column
          prop="mobile"
          header-align="center"
          align="center"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="academic"
          header-align="center"
          align="center"
          width="70"
          label="学历">
        </el-table-column>
        <el-table-column
          prop="jobGrade"
          header-align="center"
          align="center"
          width="70"
          label="职务">
        </el-table-column>
        <el-table-column
          prop="entryTime"
          header-align="center"
          align="center"
          width="100"
          label="入职时间"
          :formatter="dateFormat">
        </el-table-column>
        <el-table-column
          prop="contractExpirationTime"
          header-align="center"
          align="center"
          width="120"
          label="合同到期日期"
          :formatter="dateFormat">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="90"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      <dept-add-or-update v-if="deptAddOrUpdateVisible" ref="deptAddOrUpdate" @refreshDataList="initOrgTree"></dept-add-or-update>
      <query-model v-if="queryModelVisible" ref="queryModel" @refreshDataList="setParams"></query-model>
    </div>
</template>

<script>
  import $ from 'jquery'
  import 'vue2-org-tree/dist/style.css'
  import merge from 'lodash/merge'
  import AddOrUpdate from './../company/em/employee-add-or-update'
  import QueryModel from './../company/dept/query-model'
  import DeptAddOrUpdate from './../company/dept/deptinfo-add-or-update'
  export default {
    data () {
      return {
        visible: false,
        queryModelVisible: false,
        deptAddOrUpdateVisible: false,
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        data: {},
        horizontal: false,
        collapsable: true,
        expandAll: true,
        labelClassName: "bg-orange",
        tenantId: 0,
        deptId: '',
        params: {
          status: ''
        }
      };
    },
    components: {
      AddOrUpdate, DeptAddOrUpdate, QueryModel
    },
    watch:{
      params(){
        this.$nextTick(() => {
          this.getDataList()
        })
      }
    },
    methods: {
      init(tenantId){
        this.visible = true
        this.tenantId = tenantId
        this.initOrgTree()
        this.getDataList()
      },
      genderFormat(row, column){
        if(row.gender === 2){
          return "女"
        } else {
          return "男"
        }
      },
      setParams(params){
        this.params = params
      },
      updateParams(status){
        this.params.status = status
        this.getDataList()
      },
      dateFormat(row, column, cellValue, index){
        return cellValue? cellValue.substring(0,10):''
      },
      queryHandle(){
        this.queryModelVisible = true
        this.$nextTick(() => {
          this.$refs.queryModel.init()
        })
      },
      initOrgTree() {
        this.$http({
          url: this.$http.adornUrl('/tenant/tenantDeptInfo/tree'),
          method: 'get',
          params: this.$http.adornParams({'tenantId': this.tenantId})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.data = data.deptInfo
            this.initDrag()
          } else {
            this.data = {}
          }
        })
      },
      initDrag(){
        $("div[class^='org-tree-node']").mousedown(function(e) {
          var ele = $(this);
          document.onmousemove = function(e){
            addMoveContentControl(ele[0],e);
          }
        });
      },
      renderContent(h, data) {
        return (<el-dropdown on-command={(command) => this.onClick(command, data)}>
                  <span class="el-dropdown-link" style="color:#ffffff;">
                    {data.deptName}<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command='addChild'>添加下级部门</el-dropdown-item>
                    <el-dropdown-item v-show={data.id > 0} command='edit'>修改部门</el-dropdown-item>
                    <el-dropdown-item v-show={data.id > 0} command='del'>删除部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                )
      },
      onClick (command, node) {
        if (command === 'del') {
          if (node.children && node.children.length > 0) {
            this.$message.info('当前部门存在子部门，请先删除子部门')
          } else {
            this.$http({
              url: this.$http.adornUrl('/tenant/tenantDeptInfo/delete'),
              method: 'get',
              params: this.$http.adornParams({'id':node.id})
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message.success('删除成功')
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        }
        else if (command === 'add') {
          this.deptAddOrUpdateVisible = true
          this.$nextTick(() => {
            this.$refs.deptAddOrUpdate.init(this.tenantId, node.parentId, node.parentName)
          })
        } 
        else if (command === 'addChild') {
          this.deptAddOrUpdateVisible = true
          this.$nextTick(() => {
            this.$refs.deptAddOrUpdate.init(this.tenantId, node.id, node.deptName, 0)
          })
        } 
        else if (command === 'edit') {
          this.deptAddOrUpdateVisible = true
          this.$nextTick(() => {
            this.$refs.deptAddOrUpdate.init(this.tenantId, node.parentId, node.parentName, node.id)
          })
        }
      },
      onExpand(e, data) {
        if ("expand" in data) {
          data.expand = !data.expand;
          if (!data.expand && data.children) {
            this.collapse(data.children);
          }
        } else {
          this.$set(data, "expand", true);
        }
      },
      onNodeClick(e, data) {
        if(data.id === 0){
          this.deptId = ''
        } else {
          this.deptId = data.id
        }
        this.getDataList()
      },
      collapse(list) {
        var _this = this;
        list.forEach(function(child) {
          if (child.expand) {
            child.expand = false;
          }
          child.children && _this.collapse(child.children);
        });
      },
      expandChange() {
        this.toggleExpand(this.data, this.expandAll);
      },
      toggleExpand(data, val) {
        var _this = this;
        if (Array.isArray(data)) {
          data.forEach(function(item) {
            _this.$set(item, "expand", val);
            if (item.children) {
              _this.toggleExpand(item.children, val);
            }
          });
        } else {
          this.$set(data, "expand", val);
          if (data.children) {
            _this.toggleExpand(data.children, val);
          }
        }
      },
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/certificate/employeeInfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'tenantId': this.tenantId,
            'deptId': this.deptId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id, this.this.tenantId)
        })
      },
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm('确定要把此条信息放入垃圾箱吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'el-button--warning',
          center: true
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/certificate/employeeInfo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }

  var space = {
    move : {              // [移动]
      content : {           // [移动备注框]
        width  : 200,         // 默认div的宽度
        height : 200,         // 默认div的高度
        top    : 0 ,          // 默认div的距离头部距离
        right  : 0 ,          // 默认div的距离右侧距离
        bottom : 0 ,          // 默认div的距离底部距离
        left   : 0 ,          // 默认div的距离左侧距离
        moveHeight : 30 ,     // 默认头部高度
        textareaHeight : 170, // 默认textarea的高度
        min    : 100 ,        // div宽度高度不能小于min
        buttomTarget : null,  // 鼠标按下之后的target
        moveTarget : null     // 鼠标按下之后移动的target
      }
    }
  }
  
  /**
   * @para divEle 最大的div
   * @para e      鼠标事件
   */
  function addMoveContentSuper(divEle,e){
    // 缩小保护
    this.min = space.move.content.min;
    
    // 所有元素
    this.divEle    = divEle;
    this.textEle   = divEle.lastElementChild; // testArea element
  
    // 最大div的style
    this.divStyle  = this.divEle.style;
    this.divWidth  = this.divStyle.width;
    this.divHeight = this.divStyle.height;
    this.divTop    = this.divStyle.top;
    this.divRight  = this.divStyle.right;
    this.divBottom = this.divStyle.bottom;
    this.divLeft   = this.divStyle.left;
    
    // 头部移动高度
    this.hreadHeight = space.move.content.moveHeight;
    
    // textarray的style
    this.textStyle   = this.textEle.style;
    
    // 鼠标事件event
    this.e = e;
    this.x = e.movementX;
    this.y = e.movementY;
    this.moveTarget = space.move.content.moveTarget; // 正在移动的target
  
    // 修改属性的值  
    // [这里以后就不用再if判断了,就连html里的标签都是js生成的直接用js赋值宽度就行]
    this.divWidth  = (this.divWidth   === "") ? 
        space.move.content.width    : parseInt(this.divWidth.replace("px",""));
  
    this.divHeight = (this.divHeight  === "") ? 
        space.move.content.height   : parseInt(this.divHeight.replace("px",""));
  
    this.divTop    = (this.divTop     === "") ? 
        space.move.content.top      : parseInt(this.divTop.replace("px",""));
  
    this.divRight  = (this.divRight   === "") ? 
        space.move.content.right    : parseInt(this.divRight.replace("px",""));
  
    this.divBottom = (this.divBottom  === "") ? 
        space.move.content.bottom   : parseInt(this.divBottom.replace("px",""));
  
    this.divLeft   = (this.divLeft    === "") ? 
        space.move.content.left     : parseInt(this.divLeft.replace("px",""));
    
  }
  
  /**
   * 添加移动框的 移动 && 放大 && 缩小 && 斜拉
   * 
   * 元素组织最大一层 div → 移动层 → 八个小方位
   *                ↓
   *               textarea
   * @param  {[divElement]}  divEle [需要移动的div,最外层的div]
   * @param  {[EventObject]} e      [event type='move']
   * @return {[void]}   
   */
  function addMoveContentControl(divEle,e){
    if(e.buttons !== 1){                               // 当鼠标没有按下则不走方法
      space.move.content.moveTarget = null;
      return;
    }else if(space.move.content.moveTarget === null){  // 当鼠标按下了,movetarget为空则赋值
      space.move.content.moveTarget = e.target;        // 这里利用了成员变量
    }
    var move = divEle;                                                 // 获取移动元素
    var direction = divEle.getElementsByClassName("s-move-content-direction");           // 获取所有拉伸的节点
    switch(space.move.content.moveTarget){
      case move         : new addMoveContentMove(divEle,e,move);                break; // 头部移动
      case direction[0] : new addMoveContentTop(divEle,e,direction[0]);         break; // 上拉伸
      case direction[1] : new addMoveContentRightTop(divEle,e,direction[1]);    break; // 右上拉伸
      case direction[2] : new addMoveContentRight(divEle,e,direction[2]);       break; // 右拉伸
      case direction[3] : new addMoveContentRightButtom(divEle,e,direction[3]); break; // 右下拉伸
      case direction[4] : new addMoveContentButtom(divEle,e,direction[4]);      break; // 下拉伸
      case direction[5] : new addMoveContentLeftButtom(divEle,e,direction[5]);  break; // 左下拉伸
      case direction[6] : new addMoveContentLeft(divEle,e,direction[6]);        break; // 左上拉伸
      case direction[7] : new addMoveContentLeftTop(divEle,e,direction[7]);     break; // 左上拉伸
      default : new addMoveContentMove(divEle,e,move); 	break;
    }
  }
  
  function addMoveContentMove(divEle,e,thisEle){ // 移动
    addMoveContentSuper.apply(this,arguments); 
    var top  = this.divTop + this.y;
    var left = this.divLeft + this.x;
    this.divStyle.top  = top + "px";
    this.divStyle.left = left + "px";
  }
  
  function addMoveContentTop(divEle,e,thisEle){ // 向上拉伸
    addMoveContentSuper.apply(this,arguments);
    var top    = this.divTop;
    var height = this.divHeight + (-this.y);
    if(height < this.min)
        height = this.min;
    else
        top = this.divTop + this.y;
    this.divStyle.top    = top + "px";
    this.divStyle.height = height + "px";
    this.textStyle.height = (height - this.hreadHeight) + "px";
  }
  
  function addMoveContentRightTop(divEle,e,thisEle){ // 右上拉伸
    addMoveContentSuper.apply(this,arguments);
    var top    = this.divTop;
    var width  = this.divWidth + this.x;
    var height = this.divHeight + (-this.y);
    if(height < this.min)
        height = this.min;
    if(width < this.min)
        width = this.min;
    else
        top = this.divTop + this.y;
    this.divStyle.top    = top + "px";
    this.divStyle.width  = width + "px";
    this.divStyle.height = height + "px";
    this.textStyle.height = (height - this.hreadHeight) + "px";
  }
  
  function addMoveContentRight(divEle,e,thisEle){  // 右侧拉伸
    addMoveContentSuper.apply(this,arguments);
    var width   = this.divWidth + this.x;
    if(width < this.min)
        width = this.min;
    this.divStyle.width   = width + "px";
  }
  
  function addMoveContentRightButtom(divEle,e,thisEle){ // 右下拉伸
    addMoveContentSuper.apply(this,arguments);
    var width  = this.divWidth + this.x;
    var height = this.divHeight + this.y;
    if(height < this.min)
        height = this.min;
    if(width < this.min)
        width = this.min;
    this.divStyle.width  = width + "px";
    this.divStyle.height = height + "px";
    this.textStyle.height = (height - this.hreadHeight) + "px";
  }
  
  function addMoveContentButtom(divEle,e,thisEle){ // 向下拉伸
    addMoveContentSuper.apply(this,arguments);
    var height = this.divHeight + this.y;
    if(height < this.min)
        height = this.min;
    this.textStyle.height = (height - this.hreadHeight) + "px";
    this.divStyle.height = height + "px";
  }
  
  function addMoveContentLeftButtom(divEle,e,thisEle){ // 左下拉伸
    addMoveContentSuper.apply(this,arguments);
    var left   = this.divLeft;
    var width  = this.divWidth + (-this.x);
    var height = this.divHeight + this.y;
    if(height < this.min)
        height = this.min;
    if(width < this.min)
      width = this.min;
    else
      left = this.divLeft + this.x;
    this.divStyle.width  = width + "px";
    this.divStyle.height = height + "px";
    this.divStyle.left = left + "px";
    this.textStyle.height = (height - this.hreadHeight) + "px";
  }
  
  function addMoveContentLeft(divEle,e,thisEle){ // 向左拉伸
    addMoveContentSuper.apply(this,arguments);
    var left    = this.divLeft;
    var width   = this.divWidth + (-this.x);
    if(width < this.min)
        width = this.min;
    else
        left = this.divLeft + this.x;
    this.divStyle.left    = left + "px";
    this.divStyle.width   = width + "px";
  }
  
  function addMoveContentLeftTop(divEle,e,thisEle){ // 左上拉伸
    addMoveContentSuper.apply(this,arguments);
    var top    = this.divTop;
    var left   = this.divLeft;
    var width  = this.divWidth + (-this.x);
    var height = this.divHeight + (-this.y);
    if(height < this.min)
        height = this.min;
    else
        top = this.divTop + this.y;
    if(width < this.min)
        width = this.min;
    else
        left = this.divLeft + this.x;
    this.divStyle.top    = top + "px";
    this.divStyle.left   = left + "px";
    this.divStyle.width  = width + "px";
    this.divStyle.height = height + "px";
    this.textStyle.height = (height - this.hreadHeight) + "px";
  }

</script>

<style lang="scss">
  .demo-drawer {
        &__content {
            display: flex;
            flex-direction: column;
            height: 100%;
            form {
                flex: 1;
            }
        }
        &__footer {
            display: flex;
            button {
                flex: 1;
            }
        }
        &__header {
            text-align:right;
            margin-bottom:20px;
            width:100%;
        }
    }

    .el-drawer__body {
        padding: 20px;
    }
  .org-tree-node-label {
    white-space: nowrap;
  }
  .bg-white {
    background-color: white;
  }
  .bg-orange {
    background-color:#fc8e2d;
    color: #ffffff;
  }
  .bg-gold {
    background-color: gold;
  }
  .bg-gray {
    background-color: gray;
  }
  .bg-lightpink {
    background-color: lightpink;
  }
  .bg-chocolate {
    background-color: chocolate;
  }
  .bg-tomato {
    background-color: tomato;
  }
  .queryForm .el-form-item{
    margin-top: 20px;
    margin-bottom: 10px;
  }
  .el-button--danger {
    color: #f56c6c;
    background-color: #fff;
    border-color: #f56c6c;
  }
  .el-button--primary{
    background-color: #fc8e2d;
     border-color: #fc8e2d;
  }

  .org-tree-node-label{
    cursor: pointer;
  }
  .el-message-box__btns {
    margin-bottom: 10px;
    margin-top: 15px;
  }
  .el-message-box__title {
    margin-top: 10px;
    margin-bottom: 15px;
  }
</style>
